package com.xxyy.mylive.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;

import com.astuetz.PagerSlidingTabStrip;
import com.bumptech.glide.Glide;
import com.xxyy.mylive.MyApplication;
import com.xxyy.mylive.R;
import com.xxyy.mylive.adapter.HomeListAdapter;
import com.xxyy.mylive.bean.BaseBean;
import com.xxyy.mylive.bean.WxUserInfo;
import com.xxyy.mylive.http.HttpApi;
import com.xxyy.mylive.tools.UiTool;
import com.xxyy.mylive.ui.BaseActivity;
import com.xxyy.mylive.ui.fragment.HomeFragment;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.InflaterInputStream;

import de.hdodenhof.circleimageview.CircleImageView;

public class HomeActivity extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener, Toolbar.OnMenuItemClickListener {
    private Toolbar toolbar;
    private PagerSlidingTabStrip tabs;
    private ViewPager mViewPager;
    private Button btnStartLive;
    private FloatingActionButton fab;
//    private RecyclerView recyclerView;
//    private HomeListAdapter adapter;

    private CircleImageView userHead;
    private TextView userName, userSign;

    private MyApplication application;

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_home);
    }

    @Override
    protected void initUI() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setLogo(R.mipmap.ic_launcher);
        toolbar.inflateMenu(R.menu.activity_home_toobar);

        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        mViewPager.setAdapter(new TabAdapter(getSupportFragmentManager()));
        tabs = (PagerSlidingTabStrip) findViewById(R.id.home_tabs);
        tabs.setViewPager(mViewPager);


        fab = (FloatingActionButton) findViewById(R.id.fab);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //导航头部，用户头像、姓名、个人签名
        View headerView = navigationView.getHeaderView(0);
        userHead = (CircleImageView) headerView.findViewById(R.id.iv_user_head);
        userSign = (TextView) headerView.findViewById(R.id.tv_user_signature);
        userName = (TextView) headerView.findViewById(R.id.tv_user_name);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        btnStartLive = (Button) findViewById(R.id.btn_startLive);
    }

    @Override
    protected void initData() {
        application = (MyApplication) getApplicationContext();
        List<String> list = new ArrayList();
        list.add("fefef");
        list.add("efef");
        list.add("efef");
        list.add("efef");
        list.add("efef");

        MyApplication application = (MyApplication) getApplicationContext();
        WxUserInfo userInfo = (WxUserInfo) application.getUserInfo();
        if (null != userInfo) {
//            UiTool.showToast(this, "nickname=" + userInfo.getNickname() + "image=" + userInfo.getHeadimgurl());
            if (null != userInfo.getHeadimgurl()) {
                Glide.with(this).load(userInfo.getHeadimgurl()).into(userHead);
            }
            if (null != userInfo.getNickname()) {
                userName.setText(userInfo.getNickname());
            }
        }
    }

    @Override
    protected void setListener() {
        toolbar.setOnMenuItemClickListener(this);
        btnStartLive.setOnClickListener(this);
        tabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tabs.setTextColorResource(R.color.common_black);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "新功能即将到来········", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
//        adapter.setOnItemClickListener(new HomeListAdapter.OnItemClickListener() {
//            @Override
//            public void onItemclick(View view, int viewType) {
//                Class<?> cls = null;
//                String playUrl = "";
//                switch (viewType) {
//                    case 1001:
//                        //普通视频
//                        cls = CommonVideoActivity.class;
//                        playUrl = "http://v.1318.com/jcs_opening/160324220108031416.flv";
//                        break;
//                    case 1002:
//                        //VR视频
//                        cls = VrVideoActivity.class;
//                        playUrl = "http://v.1318.com/jcs_opening/160324220108031416.flv";
//                        break;
//                    case 1003:
//                        //直播
//                        cls = LiveVideoActivity.class;
//                        playUrl = HttpApi.RTMP_PLAY_HOST;
//                        break;
//                }
//                //进入观看直播页或视频页
//                Intent intent = new Intent(HomeActivity.this, cls);
//                intent.putExtra("play_stream", playUrl);
//                startActivity(intent);
//            }
//        });
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        } else if (id == R.id.nav_sign_out) {
            //注销,进入登录页面
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    /**
     * 获取推流地址
     *
     * @return
     */
    private String requestStreamJson() {
        try {
            // Replace "Your app server" by your app sever url which can get the StreamJson as the SDK's input.
            HttpURLConnection httpConn = (HttpURLConnection) new URL(HttpApi.RTMP_PUBLISH_HOST).openConnection();
            httpConn.setConnectTimeout(5000);
            httpConn.setReadTimeout(10000);
            int responseCode = httpConn.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                return null;
            }

            int length = httpConn.getContentLength();
            if (length <= 0) {
                return null;
            }
            InputStream is = httpConn.getInputStream();
            byte[] data = new byte[length];
            int read = is.read(data);
            is.close();
            if (read <= 0) {
                return null;
            }
            return new String(data, 0, read);
        } catch (Exception e) {
            UiTool.showToast(this, "Network error!");
        }
        return null;
    }

    private void startLive() {
        //获取rtmp直播地址，然后开始直播
        String streamJson = HttpApi.RTMP_PUBLISH_HOST;
        Intent intent = new Intent(HomeActivity.this, RecordingActivity.class);
        intent.putExtra("publish_rtmp", streamJson);
        startActivity(intent);

//        String streamJson = requestStreamJson();
//        if (null != streamJson) {
//            Intent intent = new Intent(HomeActivity.this, RecordingActivity.class);
//            intent.putExtra("publish_stream_json", streamJson);
//            startActivity(intent);
//        } else {
//            UiTool.showToast(this, "获取直播地址失败");
//        }
    }

    private class TabAdapter extends FragmentPagerAdapter implements PagerSlidingTabStrip.IconTabProvider {
        private final int[] titles = {R.drawable.twitter, R.drawable.dropbox
                , R.drawable.app_store, R.drawable.edge};

        public TabAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return new HomeFragment();
        }

        @Override
        public int getPageIconResId(int position) {
            return titles[position];
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return super.getPageTitle(position);
        }

        @Override
        public int getCount() {
            return titles.length;
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_startLive:
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) !=
                        PackageManager.PERMISSION_GRANTED) {
                    //申请直播需要的危险权限
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA
                            , Manifest.permission.WRITE_EXTERNAL_STORAGE
                            , Manifest.permission.RECORD_AUDIO}, 10);
                } else {
                    //已经授权，开始直播
                    startLive();
                }
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 10) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //授权相机成功
                startLive();
            } else {
                //拒绝授权
                UiTool.showToast(this, "无法开启直播，请允许相关权限");
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_search:
                //搜索
                UiTool.showToast(this, "搜索");
                break;
        }
        return true;
    }
}
